import {
  VxeFormProps,
  VxeFormItemProps,
  VxeFormInstance,
  VxeFormDefines,
  VxeFormListeners
} from 'vxe-pc-ui'

import { Props as DatePickerProps } from './components/date-picker/props'
import { Props as SelectModalProps } from './components/select-modal/props'
import { Props as ShiftSchedulePickerProps } from './components/shift-schedule-picker/props'

export interface Props {
  formOptions?: BasicFormProps
  formEvents?: VxeFormListeners
  searchLoading?: boolean
  /** 和search相关的按钮,用于控制按钮状态 */
  searchBtns?: string[]
  /** 统一添加clearable */
  clearable?: boolean
}

export type BasicRenderName =
  | 'ElAutocomplete'
  | 'ElInput'
  | 'ElInputNumber'
  | 'ElSelect'
  | 'ElCascader'
  | 'ElDatePicker'
  | 'ElTimePicker'
  | 'ElTimeSelect'
  | 'ElRate'
  | 'ElSwitch'
  | 'ElSlider'
  | 'ElRadioGroup'
  | 'ElCheckboxGroup'
  | 'ElButton'
  | 'ElRadio'
  | 'ElCheckbox'
  | 'ElButtons'

export type CustomRenderName =
  | 'DatePicker'
  | 'SelectModal'
  | 'ShiftSchedulePicker'
  | 'ActionButtons'

export type RenderName = BasicRenderName | CustomRenderName

type Handler<T extends any[] = any[]> = Fn<T> | PromiseFn<T>

export interface DependenciesParams<T> {
  $form: VxeFormInstance
  item: VxeFormDefines.ItemInfo & { params?: any }
  field: string
  data: T
}

// 自定义组件
interface CustomComponentProps {
  DatePickerProps: DatePickerProps
  SelectModalProps: SelectModalProps
  ShiftSchedulePickerProps: ShiftSchedulePickerProps
  // 按钮的props在children中
  ActionButtonsProps: never
}

type RenderPropsMap = {
  [K in BasicRenderName]: Recordable
} & {
  DatePicker: CustomComponentProps['DatePickerProps']
  SelectModal: CustomComponentProps['SelectModalProps']
  ShiftSchedulePicker: CustomComponentProps['ShiftSchedulePickerProps']
  ActionButtons: CustomComponentProps['ActionButtonsProps']
}

// 使用函数重载和交叉类型实现根据name类型提示不同的props
export type BasicFormItemProps<D extends Recordable = any> =
  // 基础组件类型
  | (VxeFormItemProps & {
      dependencies?: { [key: string]: Handler<[DependenciesParams<D>, any]> }
      itemRender?: {
        name: Extract<BasicRenderName, keyof RenderPropsMap>
        props?: RenderPropsMap[Extract<BasicRenderName, keyof RenderPropsMap>]
      }
    })
  // 自定义组件类型
  | (VxeFormItemProps & {
      dependencies?: { [key: string]: Handler<[DependenciesParams<D>, any]> }
      itemRender?: {
        name: Extract<CustomRenderName, keyof RenderPropsMap>
        props?: RenderPropsMap[Extract<CustomRenderName, keyof RenderPropsMap>]
      }
    })

export interface BasicFormProps<D extends Recordable = any> extends VxeFormProps<D> {
  items: BasicFormItemProps<D>[]
}
